package handingIn;

import handingIn.HandingInContainer;
import handingIn.HandingIn;
import beans.SessionManagedBean;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import lecture.Lecture;
import lecture.LectureManagedBean;
import java.util.List;
import task.ExerciseSheet;

/**
 *
 * @author Thorsten Ludwig
 */
@ManagedBean(name="uploadBean")
@ViewScoped
public class UploadManagedBean {
    
    private List<HandingInContainer> handingIns;
    
    
    public UploadManagedBean() {
        this.handingIns = this.initHandingIns();
    }
    
    
    
    
    public List<HandingInContainer> getActiveHandingIns() {
        return this.handingIns;
    }

    private List<HandingInContainer> initHandingIns() {
        Date today = new Date();
        FacesContext context = FacesContext.getCurrentInstance();        
        SessionManagedBean sb = (SessionManagedBean) context.getApplication().evaluateExpressionGet(context, "#{sessionBean}", SessionManagedBean.class);
        LectureManagedBean lb = (LectureManagedBean) sb.getLectureBean();
        Lecture lecture = lb.getLecture();
        List<ExerciseSheet> sheets = lecture.getExerciseSheets();
        List<HandingInContainer> beans = new ArrayList<HandingInContainer>();                
        String username = sb.getUser().getUsername();
        
        for (ExerciseSheet e: sheets) {
                for (HandingIn h: e.getHandingIns()) {
                    if (today.before(h.getHandingInDate()) && today.after(e.getDateOfRelease())) {
                        File f = lecture.getHandingInFile(username, e, h);
                        beans.add(new HandingInContainer(h,e,f));
                    }
                }
            
        }
        return beans;
    }
    
    public void addHandingIns() {
       
        FacesContext context = FacesContext.getCurrentInstance();        
        SessionManagedBean sb = (SessionManagedBean) context.getApplication().evaluateExpressionGet(context, "#{sessionBean}", SessionManagedBean.class);
        LectureManagedBean lb = sb.getLectureBean();
        Lecture lecture = lb.getLecture();
        String username = sb.getUser().getUsername();
        for (HandingInContainer b: this.handingIns) {
            lecture.addHandingIn(b.getSheet(), username, b.getHandingIn(), b.getFile());
        }
    }
}
